package LinkedList;

public class circleLinkedList {
    public static void main(String[] args) {
        CircleSingleList circleSingleList = new CircleSingleList();
        circleSingleList.addBoy(5);
      /*  circleSingleList.showBoy();*/
        circleSingleList.countBoy(5,20,5);
    }


}

/**
 * 创建环形的单向列表
 */
class CircleSingleList {
    //创建一个first无编号
    private Boy first = new Boy(-1);

    public void addBoy(int nums) {
        //nums做一个数据校验
        if (nums < 1) {
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy = null;
        //使用for循环来创建环形链表
        for (int i = 1; i <= nums; i++) {
            Boy boy = new Boy(i);
            if (i == 1) {
                first = boy;
                first.setNext(first);
                curBoy = first;//first不能动了 以后只跟 curBoy有关
            }
            curBoy.setNext(boy);
            boy.setNext(first);
            curBoy = boy;

        }
    }

    //遍历列表
    public void showBoy() {
        if (first == null) {
            System.out.println("链表为空");
            return;
        }
        Boy curBoy = first;
        while (true) {
            System.out.printf("小孩的编号%d\n", curBoy.getNo());
            if (curBoy.getNext() == first) {
                System.out.println("遍历完毕");
                break;
            }
            curBoy = curBoy.getNext();


        }
    }

    public void countBoy(int startNo, int countNum, int nums) {
        if (first == null || startNo < 1 || startNo > nums) {
            System.out.println("错误，重新输入");
            return;
        }
        Boy helper = first;
        while (true) {
            if (helper.getNext() == first) {
                break;
            }
            helper = helper.getNext();
        }
        //先让first移动到k这（k-1）次
        for (int i=0;i<startNo-1;i++){
            first=first.getNext();
            helper=helper.getNext();
        }
        while (true){
            if (helper==first){
                break;
            }
            for (int j=0;j<countNum-1;j++){
                first=first.getNext();
                helper=helper.getNext();
            }
            System.out.printf("小孩出圈%d\t",first.getNo());
            first=first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后幸存者%d\t",first.getNo());

    }
}


/**
 * 定义一个boy，每个HeroNode对象就是一个节点
 */
class Boy {
    private int no;
    private Boy next;

    public Boy(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }
}